package com.yj.spring.charpter02;

import cn.hutool.core.collection.CollUtil;
import com.yj.spring.common.ArgumentValue;
import com.yj.spring.common.BeanDefinition;
import com.yj.spring.common.PropertyValue;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

public class XmlBeanDefinitionReader {

    BeanFactory beanFactory;

    public XmlBeanDefinitionReader(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public void loadBeanDefinitions(Resource resource) {
        while (resource.hasNext()) {
            Element element = (Element) resource.next();
            String id = element.attribute("id").getValue();
            String className = element.attribute("class").getValue();

            List<Element> propertys = element.elements("property");
            List<Element> constructorArgs = element.elements("constructor-arg");
            List<PropertyValue> propertyValues = new ArrayList<>();
            List<ArgumentValue> argumentValues = new ArrayList<>();
            if (CollUtil.isNotEmpty(propertys)){

                for (Element property : propertys) {
                    String name = property.attribute("name").getValue();
                    String value = property.attribute("value").getValue();
                    String type = property.attribute("type").getValue();
                    PropertyValue propertyValue = new PropertyValue(name, value, type);
                    propertyValues.add(propertyValue);
                }
            }

            if (CollUtil.isNotEmpty(constructorArgs)){
                for (Element constructorArg : constructorArgs) {
                    //String name = constructorArg.attribute("name").getValue();
                    Object value = constructorArg.attribute("value").getValue();
                    String type = constructorArg.attribute("type").getValue();
                    ArgumentValue argumentValue = new ArgumentValue(value, type);
                    argumentValues.add(argumentValue);
                }
            }

            BeanDefinition beanDefinition = new BeanDefinition(id, className);
            if (CollUtil.isNotEmpty(propertyValues)){
                beanDefinition.setPropertyValues(propertyValues);
            }
            if (CollUtil.isNotEmpty(argumentValues)){
                beanDefinition.setArgumentValues(argumentValues);
            }
            beanFactory.registerBeanDefinition(beanDefinition);
        }
    }

}
